#pragma once
#include "Socket.hpp"
#include "Log.hpp"
#include "comm.hpp"
#include <functional>

using namespace LogModule;
using namespace SocketModule;

using ioservice_t = std::function<void(std::shared_ptr<Socket> &socket, InetAddr &client)>;

class TcpServer
{
public:
    TcpServer(uint16_t port)
        :_port(port),
         _tcpsocketptr(std::make_unique<TcpSocket>()),
         _isrunning(false)
    {
        _tcpsocketptr->BuildTcpSocket(_port);
    }

    void Start(ioservice_t service)
    {
        _isrunning = true;
        while(_isrunning)
        {
            InetAddr client;
            auto socket = _tcpsocketptr->Accept(&client);
            if(socket == nullptr)
            {
                continue;
            }
            LOG(LogLevel::DEBUG) << "accept success: " << client.StringAddr();
            pid_t id = fork();
            if(id < 0)
            {
                LOG(LogLevel::FATAL) << "fork failed";
                exit(FORK_ERR);
            }
            else if(id == 0)
            {
                _tcpsocketptr->Close();
                if(fork() > 0)
                {
                    exit(0);
                }

                // 孙子进程
                service(socket, client);
                socket->Close();
                exit(OK);
            }
            else
            {
                socket->Close();
                pid_t rid = ::waitpid(id, nullptr, 0);
            }
        }
        _isrunning = false;
    }

    ~TcpServer()
    {

    }
private:
    uint16_t _port;
    std::unique_ptr<Socket> _tcpsocketptr;
    bool _isrunning;
};